package com.osa.birthdaypie;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;

public class Pie extends View implements Runnable {
	private FlameProvider flameProvider;
	private List<Candle> candles;
	private Thread thread;
	private volatile boolean redraw;
	Random random = new Random();
	private PieHighlighter pieHighlighter;

	public Pie(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init();
	}

	public Pie(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	public Pie(Context context) {
		super(context);
		init();
	}

	private void init() {
		Resources resources = getResources();
		candles = new ArrayList<Candle>();
		flameProvider = new FlameProvider(resources, 5, 10);
		candles.add(new Candle(resources, flameProvider, 200, 200));
		resume();
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		mayBeInitPie();
		for (Candle candle : candles) {
			candle.prepareDrawing(0);
		}
		int pieY = getHeight() / 3;
//		Bitmap newPie = pieHighlighter.getPie(candles, pieY);
		Bitmap newPie = pieHighlighter.getPie();
		canvas.drawBitmap(newPie, 0, pieY, new Paint());
		for (Candle candle : candles) {
			candle.draw(canvas, pieY);
		}
	}
	private void mayBeInitPie(){
		if(pieHighlighter != null)
			return;
		Bitmap originalPie = BitmapFactory.decodeResource(getResources(), R.drawable.pie);
		int targetWidth = getWidth();
		int targetHeight = targetWidth * originalPie.getHeight() / originalPie.getWidth();
		System.out.println("width:" + targetWidth);
		System.out.println("height:" + targetHeight);
		pieHighlighter = new PieHighlighter(Bitmap.createScaledBitmap(originalPie, targetWidth, targetHeight, true), candles);
	}
	public void run() {
		while (redraw) {
			try {
				Thread.sleep(50);
				postInvalidate();
			} catch (InterruptedException e) {
				return;
			}
		}
	}
	public void pause(){
		if(thread != null){
			redraw = false;
			try {
				thread.join();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			thread = null;
		}
	}
	public void resume(){
		if(thread == null){
			thread = new Thread(this);
			redraw = true;
			thread.start();
		}
	}
}
